import { PlusOutlined, PaperClipOutlined,ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, Divider, Form, Space, message, TreeSelect,Modal } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { Link  ,useModel} from 'umi';

const FormItem = Form.Item;
import CreateForm from './components/CreateForm';
import BatchCreateForm from './components/BatchCreateForm';

import BatchUpdateForm from './components/BatchUpdateForm';
import UpdateForm from './components/UpdateForm';
import BatchImport from './components/BatchImport';
import { queryDevice, updateDevice, addDevice, batchUpdateState,exportDeviceExcel,batchSaveDevice,batchUpdateDevice,removeDevice,batchDelDevice } from '@/services/device';
import { queryDeviceTypeList} from '@/services/devicetype';
import { queryDriverList} from '@/services/driver';
import { queryAreaTree } from '@/services/area';

import styles from './index.less';
import { paramToString,paramToStringRemovePage } from '@/utils/utils';
import { QueryFilter, ProFormText,ProFormSelect,ProFormDatePicker } from '@ant-design/pro-form';

const { confirm } = Modal;



/**
 * 导出数据
 * @param fields
 */
 const exportDevice = async (fields: any) => {
  const hide = message.loading('导出中...');
  try {
    await exportDeviceExcel(fields);
    hide();
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};


/**
 * 添加节点
 * @param fields
 */
 const batchAdd = async (fields: any,resetForm: any) => {
  const hide = message.loading('正在添加',0);
  try {
    await batchSaveDevice(fields);
    hide();
    resetForm();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};




/**
 * 添加节点
 * @param fields
 */
const batchUpdate = async (fields: any,resetForm: any,selectedRowKeys:string) => {
  const hide = message.loading('正在更新',0);
  try {
    fields.ids=selectedRowKeys;
    await batchUpdateDevice(fields);
    hide();
    resetForm();
    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    fields.updateTime=null;
    fields.sights=null;
    console.log(fields)
    await updateDevice(fields);
    hide();

    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};


/**
 * 批量启用
 * @param fields
 */
 const toBatchUpdateState = async (fields: any) => {
  const hide = message.loading('正在更新');
  try {
    await batchUpdateState(fields);
    hide();
    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试！');
    return false;
  }
};


//删除单个
const handleRemove = async (deviceId: number) => {
  const hide = message.loading('正在删除');
  try {
    await removeDevice({ deviceId });
    hide();

    message.success('删除成功，正在刷新！');

    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};

const TableList: React.FC<{}> = (props) => {
  const { params } = props.match;
  const type=params.type!=null?Number(params.type):null;
  const { initialState } = useModel('@@initialState');
  const { dicts } = initialState || {};
  const actionRef = useRef<ActionType>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [batchCreateModalVisible, handleBatchModalVisible] = useState<boolean>(false);
  const [batchUpdateModalVisible, handleBatchUpdateModalVisible] = useState<boolean>(false);
  const [batchImportModalVisible, handleBatchImportModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});
  const [protocolConfig, setProtocolConfig] = useState([]);

  const [selectedRowKeys,setSelectedRowKeys] = useState<number[]>([]);
  const [areaId, setAreaId] = useState<string>('');
  const [typeEnumValues, setTypeEnumValues] = useState({});
  const [typeSelectValues, setTypeSelectValues] = useState([]);
  const [typeValues, setTypeValues] = useState<API.DictItem[]>([]);
  const [driverList, setDriverList] = useState<API.DriverItem[]>([]);
  const [searchDate, setSearchDate] = useState({});
  const [protocolTypeEnumValues, setProtocolTypeEnumValues] = useState({});
  const [protocolTypeSelectValues, setProtocolTypeSelectValues] = useState([]);
  const [protocolTypeValues, setProtocolTypeValues] = useState<API.DictItem[]>([]);
  const [areaEnumValues, setAreaEnumValues] = useState({});
  const [areaTreeData, setAreaTreeData] = useState<API.TreeNodeItem[]>([]);
 

  
  //批量删除
  const batchRemove = async () => {
    const hide = message.loading('正在删除');
    try {
      await batchDelDevice({ ids: selectedRowKeys.join(',')});
      setSelectedRowKeys([]);
      hide();
      message.success('删除成功，正在刷新！');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };

  const ToExport = async () => {
    const hide = message.loading('导出中');
    try {
      window.location.href="/api/exportDeviceExcel?areaId="+areaId+"&"+paramToStringRemovePage(searchDate);
      return true;
    
    } catch (error) {
      hide();
      message.error('导出失败请重试！');
      return false;
    }
  };
  const columns: ProColumns[] = [

    {
      title: '区域',
      dataIndex: 'areaId',
      valueEnum: areaEnumValues,
      //search: false,
     // hideInTable: true,
      hideInForm: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {

        return (
          <TreeSelect
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={areaTreeData}
            placeholder="请选择所在区域"
            treeDefaultExpandAll
          />
        )
      },
    },
    {
      title: '设备类型',
      dataIndex: 'deviceTypeId',
      
      valueEnum: typeEnumValues
    },    
    {
      title: '设备编号',
      dataIndex: 'deviceNo',

    },
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      render: (_,record) => 
      <Link to={'/device/details/'+record.deviceId} >  {record.deviceName}</Link>
    },  {
      title: '设备品牌',
      dataIndex: 'deviceBrand',

    },
    {
      title: '设备型号',
      dataIndex: 'deviceModel',
    },
    {
      title: '通讯协议',
      dataIndex: 'protocolType',
      valueEnum: protocolTypeEnumValues,
    },
  
    {
      title: '最新维保时间',
      dataIndex: 'latestMaintenanceTime',
      valueType: 'dateTime',
    },
    {
      title: '是否启用',
      dataIndex: 'useState',
      valueType: 'radio',
      valueEnum: {
        1: { text: '启用'},
        0: { text: '禁用'},
      }
    },
    // {
    //   title: '是否启用模拟数据',
    //   dataIndex: 'simulation',
    //   valueType: 'radio',
    //   valueEnum: {
    //     1: { text: '是'},
    //     0: { text: '否'},
    //   }
    // },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            key="editable"
            onClick={async () => {
              handleUpdateModalVisible(true);
              setFormValues(record);
            }}
          >
            编辑
          </a>  <Divider type="vertical" />
          {/* <Link to={'/device/details/'+record.deviceId} >  详情</Link> */}
         
          <a onClick={() => {
            confirm({
              title: '您确定要删除吗?',
              icon: <ExclamationCircleOutlined />,
              async onOk() {
                await handleRemove(record.deviceId);
                actionRef.current?.reload();
              },
              onCancel() {
                console.log('Cancel');
              },
            });
          }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  const onSelectChange = async (sKeys ) => {
    setSelectedRowKeys(sKeys);

  };

  useEffect(() => {
    const setSelectData = async () => {

    const deviceType = await queryDeviceTypeList();
      let tdata = {};
      let tsdata = [];
      if (deviceType && deviceType.length > 0) {
        deviceType.forEach(item => {
          tdata[item.typeId] = { text: item.typeName };
          tsdata.push({ label: item.typeName, value: item.typeId })
        });
      }
      setTypeSelectValues(tsdata);
      setTypeEnumValues(tdata);
      setTypeValues(deviceType);
     
      if(dicts){
        var  protocolType = dicts[2];
        let psdata = [];
        if (protocolType && protocolType.length > 0) {
          protocolType.forEach(item => {
            psdata.push({ label: item.dictValue, value: item.dictCode })
          });
        }
        setProtocolTypeSelectValues(psdata);
        setProtocolTypeEnumValues(dicts["2Enum"]);
        setProtocolTypeValues(protocolType);
  
      }
     
     
   
      // const protocolType = await queryDictByType({ "type": "2" });
     

      let trees = await queryAreaTree();
      let ddata = {};
      if (trees && trees.length > 0) {
        trees.forEach(item => {
          ddata[item.key] = { text: item.title };
          if (item.children != null) {
            item.children.forEach(children => {
              ddata[children.key] = { text: children.title };
            })
          }
        });
      }
      setAreaEnumValues(ddata);
      setAreaTreeData(trees);
      let driverList = await queryDriverList();
      setDriverList(driverList);

      console.log(driverList)

       localStorage.setItem("deviceTypeList",JSON.stringify(deviceType));
       localStorage.setItem("driverList",JSON.stringify(driverList));

       localStorage.setItem("areaTree",JSON.stringify(trees));
     
    };
    setSelectData();


  }, []);
 
  const reloadData =  () => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  const updateState =  async(filed ,state) => {
    let parms={ids:selectedRowKeys.join(',')};
    parms[filed]=state;
     let sucess= await toBatchUpdateState(parms);
     if(sucess){
      if (actionRef.current) {
        actionRef.current.reload();
      }
      setSelectedRowKeys([])
     }
   
  };

  
  return (
    <>
    <div style={{ padding: '20px 26px' }}>
        <QueryFilter defaultCollapsed labelWidth={'auto'} onReset ={()=> {setAreaId(''); setSearchDate({});  actionRef?.current?.reload(); } } onFinish={async (values: any) => {
           setSearchDate(values);  actionRef?.current?.reload();  }}>
             <FormItem
            label="所在区域"
            name="areaId"
          
          > <TreeSelect 
            style={{ width: '100%' }}
            onChange={(value)=>setAreaId(value)}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={areaTreeData}
            placeholder="请选择所在区域"
            treeDefaultExpandAll
          /></FormItem>
          <ProFormSelect name="deviceTypeId"  initialValue={type} label="设备类型" options={typeSelectValues} />
          <ProFormSelect name="protocolType" label="通讯协议" options={protocolTypeSelectValues} />  
          <ProFormDatePicker name="latestMaintenanceTime" label="最新维护时间" />
          <ProFormText name="deviceNo" label="设备编号" />
          <ProFormText name="deviceName" label="设备名称" />
          <ProFormText name="deviceBrand" label="设备品牌" />
          <ProFormText name="deviceModel" label="设备型号" />
        </QueryFilter>
      
      </div> 
      <ProTable
        headerTitle=""
        actionRef={actionRef}
        rowKey="deviceId"
        toolBarRender={(action, { selectedRows }) => [
          <Link  to={{
            pathname: '/device/create',
            state: { dlist:driverList},
          }} >   
          <Button icon={<PlusOutlined />}  className={styles.addBtn} 
        //  onClick={() => {handleModalVisible(true);setFormValues(createFormValues)}}
          >
            新增
          </Button>
        </Link>,
           <Button icon={<PlusOutlined />}   className={styles.addBtn} onClick={() => handleBatchModalVisible(true)}>
           批量新增
         </Button>,
          <Button icon={<PlusOutlined />}   onClick={() => handleBatchImportModalVisible(true)}  className={styles.addBtn} type="primary">
           批量导入
         </Button>,
       //  <a href={"/api/exportDeviceExcel?"+paramToString(searchDate)}>
          <Button className={styles.exportBtn}   onClick={()=>ToExport()} 
            //onClick={() => exportDevice(searchParams)}
            >
            <PaperClipOutlined />
            导出
          </Button>
       // </a>

        ]}
        toolbar={{
          settings: []
        }}
        // search={{
        //   //defaultCollapsed: false,
        //   labelWidth: 'auto',
        // }}

        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        tableAlertOptionRender={() => {
          return (
            <Space size={16}>
              {/* <a>批量删除</a> */}
              <a  onClick={() => updateState("useState",1)} >批量启用</a>
              <a  onClick={() => updateState("useState",0)} >批量停用</a>
              <a  onClick={() => handleBatchUpdateModalVisible(true)} >批量设置</a>
              {/* <a  onClick={() => updateState("simulation",1)} >启用模拟数据</a>
              <a  onClick={() => updateState("simulation",0)} >停用模拟数据</a> */}
              <a  onClick={() => {
                confirm({
                  title: '您确定要批量删除吗?',
                  icon: <ExclamationCircleOutlined />,
                  async onOk() {
                    await batchRemove();
                    actionRef.current?.reload();
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }} >批量删除</a>
            </Space>
          );
        }}
        rowSelection={{selectedRowKeys,onChange: onSelectChange}}
        search={false}
       
        request={(params) =>  queryDevice({ ...params, ...{ areaId },...{ deviceTypeId:type },...searchDate})  }
        columns={columns}
        pagination={{
          defaultCurrent: 1,
          defaultPageSize: 10,
        }}
       
      />
 {/* <Image src={ require('@/assets/device.jpg')} width={2000} preview={false} />  */}
  <BatchCreateForm
        onSubmit={async (value,resetForm) => {
          const success = await batchAdd(value,resetForm);
          if (success) {
            handleBatchModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleBatchModalVisible(false)}
        modalVisible={batchCreateModalVisible}
        devicetype={typeValues}
        protocoltype={protocolTypeValues}
        arealist={areaTreeData}
        driverList={driverList}
      />

     {selectedRowKeys && selectedRowKeys.length>0 ? (<BatchUpdateForm
        onSubmit={async (value,resetForm) => {
          const success = await batchUpdate(value,resetForm,selectedRowKeys.join(','));
          if (success) {
            setSelectedRowKeys([]);
            handleBatchUpdateModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleBatchUpdateModalVisible(false)}
        modalVisible={batchUpdateModalVisible}
        devicetype={typeValues}
        protocoltype={protocolTypeValues}
        arealist={areaTreeData}
        driverList={driverList}
      />
      ) : null}
      <BatchImport    
      onFinish={() => {handleBatchImportModalVisible(false) ; 
        if (actionRef.current) 
        {  actionRef.current.reload();  }
      }  } 
      onCancel={() => handleBatchImportModalVisible(false)}
        modalVisible={batchImportModalVisible}></BatchImport>
     {formValues && Object.keys(formValues).length ? (  <CreateForm
        onSubmit={async (value,resetForm) => {
          const success = await handleAdd(value,resetForm);
          if (success) {
            setFormValues({});
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        devicetype={typeValues}
        arealist={areaTreeData}
        protocoltype={protocolTypeValues}
        driverList={driverList}
        values={formValues}
      />      ) : null}
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
          devicetype={typeValues}
          arealist={areaTreeData}
          protocoltype={protocolTypeValues}
          driverList={driverList}
      
        />
      ) : null}
       
   
    </>
  );
};

export default TableList;
